import { response } from "express";
import { request } from "express";
import CODE from "../../config/data.config.js";
import * as service from '../../service/service.js'

class loginController {
    /**
     * @date 2023-03-14 14:39:37
     * @param {request} req 
     * @param {response} res 
     * @param {NewableFunction} next
     * @ 只能响应post请求 
     */
    static async CheckUser(req, res, next) {
        try {
            const { phone, password } = req.body;
            const result = await service.LoginService.CheckUser([phone, password]);
            if (result) {
                res.header('userid', result[0].id)
                res.status(200).send({
                    msg: '登录成功',
                    code: 1,
                    data: result
                }).end();
                return
            }
            else {
                res.removeHeader('token')
                res.status(403).send({ msg: '用户密码错误', code: 0 }).end()
                return
            }
        } catch (error) {
            next({
                status: 401,
                msg: '系统出错!',
                code: 0,
                error
            })
        }
    }

    /**
     * @date 2023-03-14 14:39:37
     * @param {Request} req 
     * @param {Response} res 
     * @param {Function} next 
     */
    static async IsUser(req, res, next) {
        try {
            const { phone } = req.body;
            const result = await service.UserService.IsExist(phone);
            if (result) {
                next();
            } else {
                res.json({
                    msg: '手机号未注册!',
                    status: 401,
                    code: 0
                }).end();
            }
        } catch (error) {
            next({
                error
            })
        }
    }

    /**
     * @date 2023-03-14 14:39:37
     * @param {request} req 
     * @ 只能响应post请求
     */
    static async IsAdmin(req, res, next) {
        try {
            const { phone } = req.body;
            const result = await service.UserService.IsExist(phone, true);
            res.header('isAdmin', result);
            next()
        } catch (error) {
            res.status(403).send(error).end();
        }
    }

    /**
     * @param {request} req 
     * @param {response} res 
     */
    static async IsFreeze(req, res, next) {
        try {
            const { phone } = req.body;
            const state = await service.UserService.IsFreeze(phone);
            if (!state) {
                next()
            } else {
                res.send({
                    msg: '该用户已冻结',
                    code: CODE.CODE_FAIL,
                    data: state
                })
            }
        } catch (error) {
            next(error)
        }
    }
}


export default loginController;